import paho.mqtt.client as mqtt
from django.conf import settings
import random
import time
import json
topic = "BOOK/WS2812B_kz"
# 订阅的 MQTT 主题
MQTT_TOPIC1 = '/writecard'  # 读卡指令的 MQTT 主题
MQTT_TOPIC2 = '/cardID'  # 卡号的 MQTT 主题
def on_connect(mqtt_client, userdata, flags, rc):
    if rc == 0:
        print('Connected successfully')
        mqtt_client.subscribe('BOOK/WS2812B_kz')
        client.subscribe(MQTT_TOPIC1)  # 订阅数据主题
        client.subscribe(MQTT_TOPIC2)  # 订阅数据主题
    else:
        print('Bad connection. Code:', rc)

# MQTT 消息处理回调函数
def on_message(mqtt_client, userdata, msg):
    print(f'Received message on topic: {msg.topic} with payload: {msg.payload}')
    from back.models import EnvironmentData, CardData

    try:
        if msg.topic == MQTT_TOPIC1:
            # 处理数据
            handle_CardData_data(msg.payload.decode())
        elif msg.topic == MQTT_TOPIC2:
            # 处理数据
            handle_environment_data(msg.payload.decode())
        else:
            print(f"Unknown topic: {msg.topic}")  # 未知主题打印警告信息

    except Exception as e:
        print(f"Error processing message from topic {msg.topic}: {e}")  # 处理消息时出现异常打印错误信息


client = mqtt.Client()
# Set CA certificate
client.tls_set(ca_certs='D:\Codes\ESP-IDF\ESP32S3\comprehensive-course-design\djangoProject\emqxsl-ca.crt')
client.on_connect = on_connect
client.on_message = on_message
client.username_pw_set(settings.MQTT_USER, settings.MQTT_PASSWORD)
client.connect(
    host=settings.MQTT_SERVER,
    port=settings.MQTT_PORT,
    keepalive=settings.MQTT_KEEPALIVE
)

def publish(client):
    msg_count = 0
    while True:
        time.sleep(1)
        msg = f"messages: {msg_count}"
        result = client.publish(topic, msg)
        # result: [0, 1]
        status = result[0]
        if status == 0:
            print(f"Send `{msg}` to topic `{topic}`")
        else:
            print(f"Failed to send message to topic {topic}")
        msg_count += 1




# 处理数据
def handle_CardData_data(payload):
    from back.models import EnvironmentData, CardData

    try:
        CardData_data = json.loads(payload)  # 解析收到的 JSON 数据
        id = CardData_data.get('id')  # ID
        species = CardData_data.get('species')  # 获取动物种类

        # 保存动物数据到数据库
        CardData = CardData.objects.create(
            card_number=id,
            information=species,
            
        )
        CardData.save()

        print(f"CardData data saved to database: {CardData}")  # 打印保存成功信息

    except json.JSONDecodeError as e:
        print(f"Error decoding JSON: {e}")  # 解析 JSON 错误打印错误信息
    except Exception as e:
        print(f"Error saving CardData data to database: {e}")  # 保存数据到数据库错误打印错误信息


# 处理读卡数据
def handle_environment_data(payload):
    from back.models import EnvironmentData, CardData

    try:
        env_data = json.loads(payload)  # 解析收到的 JSON 数据
        card_number = env_data.get('card_id')  # 获取ID
        information = env_data.get('information')  # 获取环境湿度
        timestamp = env_data.get('timestamp')  # 获取时间戳
# 检查数据库中是否已存在相同卡号的数据
        # if EnvironmentData.objects.filter(card_number=card_number).exists():
        #     print(f"EnvironmentData with card number '{card_number}' already exists. Skipping...")
        #     return
        # 保存环境数据到数据库
        environment_data = EnvironmentData.objects.create(
            card_number=card_number,
            information=information,
            timestamp=timestamp
        )
        environment_data.save()

        print(f"Environment data saved to database: {environment_data}")  # 打印保存成功信息

    except json.JSONDecodeError as e:
        print(f"Error decoding JSON: {e}")  # 解析 JSON 错误打印错误信息
    except Exception as e:
        print(f"Error saving environment data to database: {e}")  # 保存数据到数据库错误打印错误信息
